<template>
  <div class="p-6">
    <!-- 返回按钮 -->
    <el-button type="default" @click="goBack" class="mb-4"> 返回 </el-button>
    <el-card v-if="paper">
      <h2 class="text-xl font-bold mb-4">试卷名称：{{ paper.name }}</h2>
      <p class="mb-4"><strong>所属学科：</strong>{{ paper.subject }}</p>

      <div v-for="(title, index) in paper.tiTle" :key="index" class="mb-6">
        <p class="font-semibold">{{ index + 1 }}. {{ title }}</p>
        <el-input
          v-model="userAnswers[index]"
          type="textarea"
          :rows="4"
          placeholder="请输入你的答案..."
          resize="vertical"
        />
      </div>

      <el-button
        type="primary"
        :loading="submitting"
        :disabled="paper.tiTle.length === 0"
        @click="submitAnswers"
      >
        提交答卷
      </el-button>
    </el-card>

    <el-empty v-else description="正在加载试卷..." />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getPaperDetail, submitPaperAnswer } from "../api/paper";

const route = useRoute();
const router = useRouter();
const paper = ref(null);
const userAnswers = ref({});
const submitting = ref(false);

const goBack = () => {
  router.back();
};

const fetchPaper = async () => {
  const name = route.params.name;
  const res = await getPaperDetail(name);
  if (res.code === 200) {
    paper.value = res.data;
    const answerMap = {};
    res.data.tiTle.forEach((_, idx) => {
      answerMap[idx] = "";
    });
    userAnswers.value = answerMap;
  } else {
    ElMessage.error("获取试卷失败：" + (res.message || "未知错误"));
  }
};

const submitAnswers = async () => {
  submitting.value = true;
  try {
    const payload = {
      id: 0,
      studentId: 0, // 由后端解析真实值
      paperId: paper.value.id,
      studentName: "", // 由后端解析真实值
      paperName: paper.value.name,
      answerList: paper.value.tiTle.map((q, idx) => ({
        studentId: 0, // 由后端解析真实值
        title: typeof q === "string" ? q : q.title, // 如果 q 是对象取 title，否则直接用字符串
        answer: userAnswers.value[idx],
      })),
      createTime: "",
      updateTime: "",
    };

    const res = await submitPaperAnswer(payload);

    if (res.code === 200) {
      ElMessage.success("答卷提交成功！");
    } else {
      ElMessage.error("提交失败：" + (res.message || "未知错误"));
    }
  } catch (e) {
    ElMessage.error("提交过程中出错");
    console.error(e);
  } finally {
    submitting.value = false;
  }
};



onMounted(fetchPaper);
</script>
